<template>
  <el-card style="width: 1000PX;height: 1000px;">
    <!-- 第一个对话框 -->
    <el-dialog v-model="Farminglog1" title="Tips" style="height: auto;width: 500px;">
      <el-form :model="ftableData" label-width="auto" style="max-width: 600px">
        <el-form-item label="品种">
          <el-input v-model="ftableData.farming_Type" maxlength="30" />
        </el-form-item>
        <el-form-item label="来源">
          <el-input v-model="ftableData.farming_Way" maxlength="30" />
        </el-form-item>
        <el-form-item label="饲养天数">
          <el-input v-model="ftableData.farming_Days" maxlength="5" />
        </el-form-item>
        <el-form-item label="饲料品牌">
          <el-input v-model="ftableData.farming_FoodType" maxlength="30" />
        </el-form-item>
        <el-form-item label="饲养负责人">
          <el-input v-model="ftableData.farming_Fooder" maxlength="30" />
        </el-form-item>
        <el-form-item label="出栏日期">
          <el-date-picker v-model="ftableData.farming_OutintoTime" type="date" placeholder="请输入日期" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="FarmingEdit1()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <span
      style="font-size: 24px;color:dodgerblue;">养殖信息&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <el-button plain @click="Sublog1()" style="background: #f1f2f7;color:black;border:none;margin-left: 10px;">
      设置
    </el-button>
    <br />
    <!-- 六条信息显示 -->
    <span style="font-size: 16px;color: black;">
      品种:
      {{ tableData.farming_Type
      }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      来源:
      {{ tableData.farming_Way }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      饲养天数:
      {{ tableData.farming_Days }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      饲养品牌:
      {{ tableData.farming_FoodType }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      饲养负责人:
      {{ tableData.farming_Fooder }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      出栏日期:
      {{ tableData.farming_OutintoTime.toString().replace("T", " ").substring(0, 10) }}
    </span>
    <br />
    <span style="font-size: 24px;color:dodgerblue;">免疫信息&nbsp;&nbsp;</span>
    <button style="background: #f1f2f7;color:black;border:none;margin-left: 10px;" @click="addRow()">新增行</button>
    <br />
    <!-- 一条头部信息 -->
    <div style="width:100%;">
      <span style="font-size: 16px;color: black;background:#f1f2f7;padding-right: 20%;">饲养天数</span>
      <span style="font-size: 16px;color: black;background:#f1f2f7;padding-right: 18%;">保健方式</span>
      <span style="font-size: 16px;color: black;background:#f1f2f7;padding-right: 18%;">保健方法</span>
      <span style="font-size: 16px;color: black;background:#f1f2f7;">操作</span>
    </div>
    <!-- 健康信息显示，输入与显示 -->
    <el-table :data="healthydatashow" style="width: 100%">
      <el-table-column width="auto">
        <template v-slot="scope">
          <el-input v-model="scope.row.healthys_Days" v-if="scope.row.isEditing" maxlength="5"/>
          <span v-else>{{ scope.row.healthys_Days }}</span>
        </template>
      </el-table-column>

      <el-table-column width="auto">
        <template v-slot="scope">
          <el-input v-model="scope.row.healthys_Way" v-if="scope.row.isEditing" maxlength="30"/>
          <span v-else>{{ scope.row.healthys_Way }}</span>
        </template>
      </el-table-column>

      <el-table-column width="auto">
        <template v-slot="scope">
          <el-input v-model="scope.row.injection_Way" v-if="scope.row.isEditing" maxlength="30"/>
          <span v-else>{{ scope.row.injection_Way }}</span>
        </template>
      </el-table-column>
      <el-table-column width="auto">
        <template v-slot="scope">
          <!-- 打开编辑模式 -->
          <el-button type="primary" @click="scope.row.isEditing = true" v-if="!scope.row.isEditing"
            style="width: 30px;">
            修改
          </el-button>
          <el-button type="danger" @click="DelHelthy(scope.row.rabit_Batch, scope.row.healthys_Id)"
            v-if="!scope.row.isEditing" style="width: 30px;">
            删除
          </el-button>
          <el-button type="primary" @click="Save(scope.row.rabit_Batch, scope.row, scope.row.isEditing = false)"
            v-if="scope.row.isEditing" style="width: 30px;">
            保存
          </el-button>
          <el-button type="danger" @click="Remove(scope.$index, scope.row.isEditing = false)" v-if="scope.row.isEditing"
            style="width: 30px;">
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <span style="font-size: 24px;color:dodgerblue;">动检证&nbsp;&nbsp;</span>
    <br />
    <!-- 利用数组的上传 -->
    <span style="font-size: 16px;color: black;">
      <!-- 图片预览地址 -->
      <el-dialog v-model="dialogVisible1">
        <img w-full :src="dialogImageUrl1" />
      </el-dialog>
      <!-- 上传图片以','分开存储字符串 -->
      <el-upload class="avatar-uploader" v-model:file-list="fileList1" action="http://localhost:5094/api/Fileall/Fileup"
        :on-success="handleAvatarSuccess1" list-type="picture-card" :before-upload="beforeAvatarUpload1"
        :on-remove="handleRemove1" :on-preview="handlePictureCardPreview1" :limit="9">

        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

    </span>
    <br />
    <el-dialog v-model="Farminglog2" title="Tips" style="height: auto;width: 500px;">
      <el-form :model="ftableData" label-width="auto" style="max-width: 600px">
        <el-form-item label="养殖场">
          <el-input v-model="FnextWortk.farming_Please" maxlength="30"/>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="FnextWortk.farming_People" maxlength="30"/>
        </el-form-item>
        <el-form-item label="存栏数量">
          <el-input v-model="FnextWortk.farming_SaveCout" maxlength="5"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="FarmingEdit2()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <span style="font-size: 24px;color:dodgerblue;">企业信息&nbsp;&nbsp;</span>
    <button style="background: #f1f2f7;color:black;border:none;margin-left: 10px;" @click="Sublog2()">设置</button>
    <br />
    <!-- 三条信息显示 -->
    <span style="font-size: 16px;color: black;">
      养殖场:
      {{ NextWortk.farming_Please
      }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      负责人:
      {{ NextWortk.farming_People }}
    </span>
    <br />
    <span style="font-size: 16px;color: black;">
      存栏数量:
      {{ NextWortk.farming_SaveCout }}
    </span>
    <br />
    <span style="font-size: 24px;color:dodgerblue;">企业照片&nbsp;&nbsp;</span>
    <br />
    <!-- 利用数组的上传 -->
    <span style="font-size: 16px;color: black;">
      <!-- 图片预览地址 -->
      <el-dialog v-model="dialogVisible2">
        <img w-full :src="dialogImageUrl2" />
      </el-dialog>
      <!-- 上传图片以','分开存储字符串 -->
      <el-upload class="avatar-uploader" v-model:file-list="fileList2" action="http://localhost:5094/api/Fileall/Fileup"
        :on-success="handleAvatarSuccess2" list-type="picture-card" :before-upload="beforeAvatarUpload2"
        :on-remove="handleRemove2" :on-preview="handlePictureCardPreview2" :limit="9">

        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

    </span>
  </el-card>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'

const Farminglog1 = ref(false)
const Farminglog2 = ref(false)
//用于显示数据和判断数据
const tableData = reactive({
  farming_Id: 0,
  rabit_Batch: location.search.split("=")[1],
  farming_Type: "",
  farming_Way: "",
  farming_Days: 0,
  farming_FoodType: "",
  farming_Fooder: "",
  farming_OutintoTime: "",
  farming_Img: "",
  company_Img: "",
  farming_Isdel: false
})//修改添加数据
const ftableData = reactive({
  farming_Id: 0,
  rabit_Batch: location.search.split("=")[1],
  farming_Type: "",
  farming_Way: "",
  farming_Days: 0,
  farming_FoodType: "",
  farming_Fooder: "",
  farming_OutintoTime: "",
  farming_Img: "",
  company_Img: "",
  farming_Isdel: false
})

const NextWortk = reactive({
  "farmings_Next_Id": 0,
  "rabit_Batch": location.search.split("=")[1],
  "farming_Please": "",
  "farming_People": "",
  "farming_SaveCout": 0
})
const FnextWortk = reactive({
  "farmings_Next_Id": 0,
  "rabit_Batch": location.search.split("=")[1],
  "farming_Please": "",
  "farming_People": "",
  "farming_SaveCout": 0
})
onMounted(() => {
  FirstShow1()
  ShowHealthy()
  ShowNext()
})//打开第一个养殖弹窗
const Sublog1 = () => {
  Farminglog1.value = true
}
const Sublog2 = () => {
  Farminglog2.value = true
}
//如果有id值了，就修改，没有就新增,不用变动
const FarmingEdit1 = () => {
    if (isNaN(ftableData.farming_Days)||ftableData.farming_Type == "" || ftableData.farming_Way == ""|| ftableData.farming_FoodType == "" || ftableData.farming_Fooder == "" ||ftableData.farming_OutintoTime == "") {
    ElMessage.error("信息不能为空")
       return
  }
  if (tableData.farming_Id == 0) {//添加养殖表数据
    axios.post("http://localhost:5094/api/FamingAll/AddFaming", ftableData)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow1()
        ftableData.farming_Type = ""
        ftableData.farming_Way = ""
        ftableData.farming_Days = 0
        ftableData.farming_FoodType = ""
        ftableData.farming_Fooder = ""
        ftableData.farming_OutintoTime = ""
        ftableData.farming_Isdel = false
        Farminglog1.value = false
      })
  }
  else {//修改养殖表数据
    ftableData.farming_Id = tableData.farming_Id
    axios.post("http://localhost:5094/api/FamingAll/UpdateFaming", ftableData)
      .then(res => {
        ElMessage.success(res.data.message)
        FirstShow1()
        ftableData.farming_Type = ""
        ftableData.farming_Way = ""
        ftableData.farming_Days = 0
        ftableData.farming_FoodType = ""
        ftableData.farming_Fooder = ""
        ftableData.farming_OutintoTime = ""
        ftableData.farming_Isdel = false
        Farminglog1.value = false
      })
  }
}//提交养殖信息2
const FarmingEdit2 = () => {
       if (isNaN(FnextWortk.farming_SaveCout)||FnextWortk.farming_People == "" || FnextWortk.farming_Please == "" ) {
    ElMessage.error("信息不能为空，天数必须为数字")
       return
  }
  if (NextWortk.farmings_Next_Id == 0) {//公司表数据
    axios.post("http://localhost:5094/api/Farmings_NextAll/AddNextWay", FnextWortk)
      .then(res => {
        ElMessage.success(res.data.message)
        ShowNext()
        FnextWortk.farming_Please = ""
        FnextWortk.farming_People = ""
        FnextWortk.farming_SaveCout = 0
        Farminglog2.value = false
      })
  }
  else {//修改公司表数据
    FnextWortk.farmings_Next_Id = NextWortk.farmings_Next_Id
    axios.post("http://localhost:5094/api/Farmings_NextAll/UpdateNextWay", FnextWortk)
      .then(res => {
        ElMessage.success(res.data.message)
        ShowNext()
        FnextWortk.farming_Please = ""
        FnextWortk.farming_People = ""
        FnextWortk.farming_SaveCout = 0
        Farminglog2.value = false
      })
  }
}
//填充养殖数据
const FirstShow1 = () => {
  axios.get("http://localhost:5094/api/FamingAll/FirstFarming", {
    params: {
      Batch: tableData.rabit_Batch
    }
  }).then(res => {
    ElMessage.success(res.data.message)
    if (res.data.data != null)
      tableData.farming_Id = res.data.data.farming_Id
    tableData.farming_Type = res.data.data.farming_Type
    tableData.farming_Way = res.data.data.farming_Way
    tableData.farming_Days = res.data.data.farming_Days
    tableData.farming_FoodType = res.data.data.farming_FoodType
    tableData.farming_Fooder = res.data.data.farming_Fooder
    tableData.farming_OutintoTime = res.data.data.farming_OutintoTime
    ftableData.farming_Img = res.data.data.farming_Img//实际用于添加的养殖的数据
    ftableData.company_Img = res.data.data.company_Img//实际用于添加的养殖的数据
    tableData.farming_Isdel = res.data.data.farming_Isdel
    initImageList1()
    initImageList2()
  })
}
//显示健康数据
const healthydatashow = ref([{
  healthys_Id: 0,
  rabit_Batch: tableData.rabit_Batch.toString(),
  healthys_Days: 0,
  healthys_Way: "",
  injection_Way: "",
  isEditing: true,
  isDel: false
}])
//添加一行
const addRow = () => {
  healthydatashow.value.push({
    healthys_Id: 0,
    rabit_Batch: tableData.rabit_Batch.toString(),
    healthys_Days: 0,
    healthys_Way: "",
    injection_Way: "",
    isEditing: true,
    isDel: false
  })
};
//删除一行
const Remove = (index: number, sf: boolean) => {
  healthydatashow.value.splice(index, 1)
}//添加健康信息
const Save = (id: number, row: any, sf: boolean) => {
  if (isNaN(row.healthys_Days)|| row.healthys_Way == "" || row.injection_Way == "") {
    ElMessage.error("信息不能为空,天数必须为数字")
    ShowHealthy()
  }
  else{  if (id == 0) {
    axios.post("http://localhost:5094/api/HealthyAll/AddHealthy", row)
      .then(res => {
        ElMessage.success("保存成功")
        ShowHealthy()
      })
  }
  else {//修改健康信息
    axios.post("http://localhost:5094/api/HealthyAll/UpdateHealthy", row)
      .then(res => {
        ElMessage.success("保存成功")
        ShowHealthy()
      })
  }}
window.location.href="/FarmingsAll?Batch="+tableData.rabit_Batch.toString()
}//显示健康信息
const ShowHealthy = () => {
  axios.get("http://localhost:5094/api/HealthyAll/ShowHealthy", {
    params: {
      Batch: tableData.rabit_Batch
    }
  }).then(res => {
    if (res.data.data != null)
      healthydatashow.value = res.data.data
  })
}//删除健康信息
const DelHelthy = (Batch: string, id: number) => {
  if (!confirm("确定删除吗？"))
    return
  else {
    axios.get("http://localhost:5094/api/HealthyAll/DelHealthy", {
      params: {
        Batch: Batch,
        id: id
      }
    }).then(res => {
      ElMessage.success(res.data.message)
      ShowHealthy()
    })
  }
}//填充养殖信息2
const ShowNext = () => {
  axios.get("http://localhost:5094/api/Farmings_NextAll/FirstNextWay", {
    params: {
      Batch: tableData.rabit_Batch
    }
  }).then(res => {
    if (res.data.data != null)
      NextWortk.farmings_Next_Id = res.data.data.farmings_Next_Id
    NextWortk.farming_Please = res.data.data.farming_Please
    NextWortk.farming_People = res.data.data.farming_People
    NextWortk.farming_SaveCout = res.data.data.farming_SaveCout
  })
}
//限制动检证的图片
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}//限制企业照片的图片
const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}
const fileList1 = ref<UploadUserFile[]>([])
const fileList2 = ref<UploadUserFile[]>([])
// 初始化图片列表
const initImageList1 = () => {
  if (ftableData.farming_Img && ftableData.farming_Img !== '') {
    const imageUrls = ftableData.farming_Img.split(',').filter(url => url.trim() !== '')
    fileList1.value = imageUrls.map((url, index) => ({
      name: `image_${index + 1}.jpg`,
      url: url.trim()
    }))
  } else {
    fileList1.value = []
  }
}
// 初始化图片列表
const initImageList2 = () => {
  if (ftableData.company_Img && ftableData.company_Img !== '') {
    const imageUrls = ftableData.company_Img.split(',').filter(url => url.trim() !== '')
    fileList2.value = imageUrls.map((url, index) => ({
      name: `image_${index + 1}.jpg`,
      url: url.trim()
    }))
  } else {
    fileList2.value = []
  }
}
// 添加新上传的图片到数组，并更新到数据库中
const handleAvatarSuccess1: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  const newImageUrl = response.data
  if (ftableData.farming_Img && ftableData.farming_Img !== '') {
    ftableData.farming_Img += ',' + newImageUrl
  } else {
    ftableData.farming_Img = newImageUrl
  }

  // 保存到数据库
  saveImagesToDatabase1()

  ElMessage.success('图片上传成功')
}
const handleAvatarSuccess2: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // 再次检查图片数量限制（双重保险）
  const currentImageCount = ftableData.company_Img ?
    ftableData.company_Img.split(',').filter(url => url.trim() !== '').length : 0
  if (currentImageCount >= 9) {
    ElMessage.error('最多只能上传9张图片')
    return
  }
  const newImageUrl = response.data
  if (ftableData.company_Img && ftableData.company_Img !== '') {
    ftableData.company_Img += ',' + newImageUrl
  } else {
    ftableData.company_Img = newImageUrl
  }

  // 保存到数据库
  saveImagesToDatabase2()

  ElMessage.success('图片上传成功')
}

const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 从数组中移除对应的图片URL
  const imageUrls = ftableData.farming_Img.split(',').filter(url => url.trim() !== '')
  const index = imageUrls.findIndex(url => url === uploadFile.url)

  if (index > -1) {
    imageUrls.splice(index, 1)
    ftableData.farming_Img = imageUrls.join(',')
    // 更新数据库
    saveImagesToDatabase1()
    ElMessage.success('图片删除成功')
  }
}
const handleRemove2: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 从数组中移除对应的图片URL
  const imageUrls = ftableData.company_Img.split(',').filter(url => url.trim() !== '')
  const index = imageUrls.findIndex(url => url === uploadFile.url)
  
  if (index > -1) {
    imageUrls.splice(index, 1)
    ftableData.company_Img = imageUrls.join(',')
    // 更新数据库
    saveImagesToDatabase2()
    ElMessage.success('图片删除成功')
  }
}
// 保存图片数组到数据库1
const saveImagesToDatabase1 = () => {
  axios.get('http://localhost:5094/api/FamingAll/CheckFarming', {
    params: {
      Batch: ftableData.rabit_Batch,
      CheckImages: ftableData.farming_Img
    }
  }).then(res => {
    ElMessage.success('图片保存成功')
  }).catch(err => {
    ElMessage.error('图片保存失败: ' + err.message)
  })
}// 保存图片数组到数据库2
const saveImagesToDatabase2 = () => {
  axios.get('http://localhost:5094/api/FamingAll/CheckCompany', {
    params: {
      Batch: ftableData.rabit_Batch,
      CheckImages: ftableData.company_Img
    }
  }).then(res => {
      ElMessage.success('图片保存成功')
  }).catch(err => {
    ElMessage.error('图片保存失败: ' + err.message)
  })
}
//图片地址
const dialogImageUrl1 = ref('')
//图片弹窗
const dialogVisible1 = ref(false)
//图片地址
const dialogImageUrl2 = ref('')
//图片弹窗
const dialogVisible2 = ref(false)
//图片预览1
const handlePictureCardPreview1: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!
  dialogVisible1.value = true
}
//图片预览2
const handlePictureCardPreview2: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl2.value = uploadFile.url!
  dialogVisible2.value = true
}
</script>

<!-- 使用黑色实线边框,加号，边框 -->
<style>
.avatar-uploader .el-upload {
  border: 1px solid var(--el-border-color);
  border-color: black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 17px;
  color: black;
  width: 17px;
  height: 17px;
  text-align: center;
}
</style>